package com.yz.hoo;

import com.alibaba.fastjson.JSONObject;
import com.yz.common.R;
import com.yz.util.EmptyUtil;
import com.yz.util.Md5Util;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.yz.util.RSAUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HooUtil {
    private static final Logger logger = LoggerFactory.getLogger(HooUtil.class);
    static Pattern pattern = Pattern.compile("\\\\u([0-9a-fA-F]{4})");


    public static String getParamSignStr(Map<String, Object> params) {
        if (params != null && params.size() != 0) {
            StringBuilder paramStr = new StringBuilder();
            TreeSet<String> treeSet = new TreeSet();
            treeSet.addAll(params.keySet());
            Iterator ite = treeSet.iterator();

            while(ite.hasNext()) {
                String paramKey = (String)ite.next();
                paramStr.append(paramKey + "=" + params.get(paramKey) + "&");
            }

            paramStr.deleteCharAt(paramStr.length() - 1);
            return paramStr.toString();
        } else {
            return "";
        }
    }

    public static String getSign(String paramStr, String key) {
        return Md5Util.MD5(Md5Util.MD5(key + paramStr) + key);
    }

    public static Map<String, String> getParamMap(Map<String, Object> params, String key) {
        if (params != null && params.size() != 0) {
            StringBuilder paramStr = new StringBuilder();
            Map<String, String> nParams = new HashMap();
            TreeSet<String> treeSet = new TreeSet();
            treeSet.addAll(params.keySet());
            Iterator ite = treeSet.iterator();

            String sign;
            while(ite.hasNext()) {
                sign = (String)ite.next();
                paramStr.append(sign + "=" + params.get(sign) + "&");
                nParams.put(sign, String.valueOf(params.get(sign)));
            }

            paramStr.deleteCharAt(paramStr.length() - 1);
            logger.info("签名字符串：{}", paramStr.toString());
            sign = getSign(paramStr.toString(), key);
            logger.info("签名：{}", sign);
            nParams.put("sign", sign);
            logger.info("请求参数：{}", nParams);
            return nParams;
        } else {
            return null;
        }
    }

    public static String getpath(String intfName, String ip) {
        String url = ip + intfName;
        logger.info("请求地址：{}", url);
        return url;
    }

    public static R<JSONObject> handleResult(String result) {
        if (EmptyUtil.isEmpty(result)) {
            return R.error("结果为空！");
        } else {
            JSONObject jo = JSONObject.parseObject(result);
            String status = jo.getString("status");
            return "0".equals(status) ? R.okData(jo) : R.error(jo.getString("msg")).setData(jo);
        }
    }

    public static boolean verify(Map<String, Object> params) {
        String sign = (String)params.get("sign");
        if (EmptyUtil.isEmpty(sign)) {
            logger.info("验签失败！");
            return false;
        } else {
            String hoo_sign = (String)params.get("hoo_sign");
            if (EmptyUtil.isEmpty(hoo_sign)) {
                params.remove("sign");
                hoo_sign = getParamSignStr(params);
            }

            logger.info("验签字符串:{}", hoo_sign);
            if (!sign.equalsIgnoreCase(getSign(hoo_sign, "12345678"))) {
                logger.info("验签失败！");
                return false;
            } else {
                logger.info("验签成功！");
                return true;
            }
        }
    }

    public static boolean verifyByRsa(Map<String,Object> params){
        return true;
    }

    public static String escapeJson(String str) {
        StringBuffer b = new StringBuffer();
        Matcher m = pattern.matcher(str);

        while(m.find()) {
            b.append((char)Integer.parseInt(m.group(1), 16));
        }

        return b.toString();
    }
    public static Map<String, Object> convertToMap(Object obj)
            throws Exception {

        Map<String, Object> map = new HashMap<>();
        Field[] fields = obj.getClass().getDeclaredFields();
        for (int i = 0, len = fields.length; i < len; i++) {
            String varName = fields[i].getName();
            boolean accessFlag = fields[i].isAccessible();
            fields[i].setAccessible(true);
            Object o = fields[i].get(obj);
            if (o != null) {
                map.put(varName, o.toString());
            }
            fields[i].setAccessible(accessFlag);
        }
        return map;
    }

    /**
     * 将16进制字符串还原为字节数组.
     */
    public static final byte[] hexStrToBytes(String s)  {
        byte[] bytes;
        bytes = new byte[s.length() / 2];
        for (int i = 0; i < bytes.length; i++){
            bytes[i] = (byte) Integer.parseInt(s.substring(2 * i, 2 * i + 2), 16);
        }
        return bytes;
    }

    public static void main(String[] args) throws Exception {
        String publicKey = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAMXblk3LWzYfa/q1bQVmSrnj38fDEwZ3Wg8ZUCo72gKg7ErhipDZarAXzr4dkiF3VaAihXrqZIYTbzOru6bd+CkCAwEAAQ==";
        String data = "Jg7CWHvzlx6zH47ITooK61X6XjHMr8Jo86P/RG2DSYVF7IbLLba9EeZ+aWGhNQw5CUGwrHtjIywn9DcxzieSfw==";
        String sign = "nGGyhyBzqzCwOFIDWRRxvBaqycOU2sMjY/arc8navxGkoHtChqoEPzW8yeTWBic16qL7NSJJDOLJvACUjxncgA==";
        System.out.println(RSAUtil.verify(data.getBytes(),publicKey,sign));

    }


}
